package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Permission;
import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequirePermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    @RequirePermission(name = "角色查询",expression = "role:list")
    @RequestMapping("/list")
    public String selectList(@ModelAttribute("qo") QueryObject qo, Model model){
        PageInfo<Role> pageInfo = roleService.queryPage(qo);
        model.addAttribute("pageInfo",pageInfo);
        return "/role/list";
    }

    @RequirePermission(name = "角色删除",expression = "role:delete")
    @RequestMapping("/delete")
    public String delete(Long id){
        roleService.delete(id);
        return "redirect:/role/list";
    }

    @RequirePermission(name = "角色新增/编辑",expression = "role:savOrUpdate")
    @RequestMapping("/input")
    public String input(Long id,Model model){
        //查权限列表用于回显
        List<Permission> permissions = permissionService.selectAll();
        model.addAttribute("permissions",permissions);

        if (id != null){
            //根据id查角色信息
            Role role = roleService.selectOne(id);
            model.addAttribute("role",role);

            //根据id查角色拥有的权限
        }
        return "/role/input";
    }

    @RequirePermission(name = "角色新增/编辑",expression = "role:savOrUpdate")
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Role role,Long[] ids){
        roleService.saveOrUpdate(role,ids);
        return "redirect:/role/list";
    }
}
